package com.authapi.sample.api.controller;

import com.authapi.sample.api.entity.Client;
import com.authapi.sample.api.entity.Role;
import com.authapi.sample.api.entity.User;
import com.authapi.sample.api.model.Response.Client.ClientRequest;
import com.authapi.sample.api.model.Response.Common.Result;
import com.authapi.sample.api.model.Response.Common.ResultList;
import com.authapi.sample.api.model.Response.Role.QueryRoleRequest;
import com.authapi.sample.api.service.impl.ClientServiceImpl;
import com.authapi.sample.api.service.impl.RoleServiceImpl;
import com.authapi.sample.api.utils.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Baomidou
 * @since 2024-12-11
 */
@RestController
@RequestMapping("/client")
@Api(tags = "客户端管理")
public class ClientController {
    @Autowired
    private ClientServiceImpl clientService;

    @GetMapping("/GetClient")
    public Result<Client> GetClient(String id){
        Client client = clientService.getById(id);
        return Result.Success(client);
    }

    @PostMapping("/AddClient")
    public Result<Client> addClient(@RequestBody Client client){
        if(client.getId()==null|| client.getId().isEmpty()){
            client.setId(UUID.randomUUID().toString().substring(0,6));
        }
        clientService.save(client);
        return Result.Success(client);
    }

    @PostMapping("/UpdateClient")
    public Result<Client> UpdateClient(@RequestBody Client client){
        clientService.updateById(client);
        return Result.Success(client);
    }

    @PostMapping("/DeleteClient")
    public Result<User> DeleteClient(@RequestBody Client client){
        clientService.removeById(client.getId());
        return Result.Success(null);
    }

    @PostMapping("/QueryClient")
    public ResultList<List<Client>> QueryClient(@RequestBody ClientRequest request){
        int pageIndex = PageUtil.getPageIndexFromHeader();
        int pageSize = PageUtil.getPageSizeFromHeader();
        Page<Client> page = new Page<>(pageIndex, pageSize);
        QueryWrapper<Client> queryWrapper = new QueryWrapper<>();
        if(!request.getName().isEmpty()){
            queryWrapper.eq("name", request.getName());
        }

        IPage<Client> clientPage = clientService.page(page,queryWrapper);
        int count =(int) clientService.count(queryWrapper);
        List<Client> result = clientPage.getRecords();
        return ResultList.Success(result, count);
    }
}
